package com.copa.gamestore.module.cart.application.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.gamestore.common.response.ResponseVo;
import com.copa.gamestore.module.cart.application.CartApplicationService;
import com.copa.gamestore.module.cart.domain.Cart;
import com.copa.gamestore.module.cart.dto.CartDto;
import com.copa.gamestore.module.cart.mapper.CartMapper;
import com.copa.gamestore.module.cart.service.CartService;
import com.copa.gamestore.module.cart.vo.CartVo;
import com.copa.gamestore.module.gameGoods.application.GameGoodsApplicationService;
import com.copa.gamestore.module.user.application.UserApplicationService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author copa
 * @createDate 2022-09-27 11:32
 * @function
 */
@Service
public class CartApplicationServiceImpl implements CartApplicationService {

    @Resource
    private CartService cartService;

    @Resource
    private CartMapper cartMapper;

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private GameGoodsApplicationService gameGoodsApplicationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseVo<String> post(CartDto cartDto) {
        cartDto.setUserId(userApplicationService.userInfo().getId());
        // 这里减库存有些不妥，应该在下单时减库存
        //gameGoodsApplicationService.stock(cartDto.getGameGoodsId(), cartDto.getNum());
        cartService.post(cartDto);
        return ResponseVo.successMsg("添加到购物车成功~");
    }

    @Override
    public ResponseVo<CartVo> get() {
        Long userId = userApplicationService.userInfo().getId();
        return ResponseVo.success(cartService.getCartGoodsVo(userId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseVo<String> delete(List<Long> ids) {
        Long userId = userApplicationService.userInfo().getId();
        cartService.delete(ids, userId);
        return ResponseVo.success("修改成功~");
    }

    @Override
    public void validateUser(List<Long> cartIds) {
        Long userId = userApplicationService.userInfo().getId();
        cartService.validateUser(cartIds, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByOrder(List<Long> ids) {
        Long userId = userApplicationService.userInfo().getId();
        cartMapper.delete(new QueryWrapper<Cart>().eq("user_id", userId).in("id", ids));
    }
}
